<template>
    <div>
        <!--卡片-->
        <el-card class="box-card">
            <!--定义面包屑-->
            <el-breadcrumb separator=">">
                <el-breadcrumb-item :to="{ path: '/master' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>系统管理</el-breadcrumb-item>
                <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            </el-breadcrumb>
            <el-divider></el-divider>
            <!--表单的搜索框
                 :model="双向绑定表单的数据"
            -->
            <el-form :inline="true" :model="userFormData"  class="demo-form-inline">
                <el-form-item >
                    <el-input v-model="userFormData.userName" placeholder="请输入登陆名"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="userFormData.loginName" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="userFormData.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-input v-model="userFormData.phone" placeholder="请输入电话"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="initUser()">查询</el-button>
                    <el-button type="primary" @click="editUserDialog=true">添加</el-button>
                </el-form-item>
            </el-form>

            <!--数据表格-->
            <template>
                <el-table
                        :data="tableData"
                        :border="true"
                        stripe
                        style="width: 100%">
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-form label-position="left" inline class="demo-table-expand">
                                <el-form-item label="用户Id">
                                    <span>{{ props.row.userId }}</span>
                                </el-form-item>
                                <el-form-item label="登陆账号">
                                    <span>{{ props.row.userName }}</span>
                                </el-form-item>
                                <el-form-item label="性别">
                                    <span>{{ props.row.sex==1?'女':'男'}}</span>
                                </el-form-item>
                                <el-form-item label="邮箱">
                                    <span>{{ props.row.email}}</span>
                                </el-form-item>
                                <el-form-item label="电话">
                                    <span>{{ props.row.phonenumber}}</span>
                                </el-form-item>
                                <el-form-item label="备注">
                                    <span>{{ props.row.remark}}</span>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="userId"
                            label="编号"
                            width="40">
                    </el-table-column>
                    <el-table-column
                            prop="avatar"
                            label="头像"
                            align="center"
                            width="80px"
                            >
                        <template slot-scope="scope">
                            <img :src="scope.row.avatar" width="80px" height="60px" class="avatars">
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="userName"
                            label="账号"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="loginName"
                            label="昵称">
                    </el-table-column>
                    <el-table-column
                            prop="sex"
                            label="性别">
                        <template slot-scope="scope">
                            {{ scope.row.sex==1 ? '女' : '男' }}
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="email"
                            label="邮箱">
                    </el-table-column>
                    <el-table-column
                            prop="phonenumber"
                            label="手机号">
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="状态">
                        <template slot-scope="scope">
                            <el-switch
                                    v-model="scope.row.status"
                                    active-color="#13ce66"
                                    active-value="0"
                                    inactive-value="1"
                                    inactive-color="#ff4949"
                                    @change="switchStatus(scope.row.userId,$event)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            label="创建时间">
                    </el-table-column>
                    <el-table-column
                            prop="updateTime"
                            label="修改时间">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="primary" icon="el-icon-edit" @click="selById(scope.row.userId)" circle></el-button>
                            <el-button type="danger" icon="el-icon-delete" @click="del(scope.row.userId)" circle></el-button>
                            <el-button type="warning" icon="el-icon-star-off" circle @click="showUserRole(scope.row.userId)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页-->
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </template>
        </el-card>
        <!--分配角色的弹出框-->
        <el-dialog
                title="分配用户角色"

                :visible.sync="fenRoleDialog"
                width="30%"
                >
            <el-checkbox-group v-model="userRole" >
                <el-checkbox v-for="role in roleAll" :label="role.roleId" :key="role.roleId">{{role.roleName}}</el-checkbox>
            </el-checkbox-group>
            <span slot="footer" class="dialog-footer">
            <el-button @click="fenRoleDialog = false">取 消</el-button>
            <el-button type="primary" @click="confirmFenRole">确 定</el-button>
          </span>
        </el-dialog>
        <!--                更新用户信息表单-->
        <el-dialog
                title="添加用户"
                :visible.sync="editUserDialog"
                width="30%"
                :before-close="handleClose">
            <!--            model表单数据-->
            <el-form  label-width="80px" :model="userForm" :rules="userFormRules" ref="userFormRef">
                <el-form-item label="头像" prop="avatar">
                    <el-upload
                            class="avatar-uploader"
                            action="http://localhost:80/system/user/upPicture"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                            :headers="{'token':token}">
                        <img v-if="userForm.avatar" :src="userForm.avatar"  width="80px" border="1px">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item label="登录名" prop="loginName">
                    <el-input v-model="userForm.loginName"></el-input>
                </el-form-item>
                <el-form-item label="登陆账号" prop="userName">
                    <el-input v-model="userForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="userForm.sex" >
                        <el-radio label="0">男</el-radio>
                        <el-radio label="1">女</el-radio>
                        <el-radio label="2">其他</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="手机号" prop="phonenumber">
                    <el-input v-model="userForm.phonenumber"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="userForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                        <el-button @click="resetForm()">取 消</el-button>
                        <el-button type="primary" @click="editUserBtn">确 定</el-button>
                    </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Users",
        data(){
            let validateAnotherUserName = (rule, value, callback) => {
                //查询用户名是否重复
                this.$http.post(`/system/user/selUserName`,this.userForm).then(function (res) {
                    if (res && res.data.result.code == '0') {
                        callback()
                    } else if (res && res.data.result.code == '1') {
                        callback(new Error('账号已存在'))
                    }

                })
            }
            let validateAnotherPhone = (rule, value, callback) => {
                //查询手机号是否重复
                this.$http.post(`/system/user/selPhone`,this.userForm).then(function (res) {
                    if (res && res.data.result.code == '0') {

                        callback()
                    } else if (res && res.data.result.code == '1') {
                        callback(new Error('手机号已存在'))
                    }

                })
            }
            let validateAnotherEmail = (rule, value, callback) => {
                //查询邮箱是否重复
                this.$http.post(`/system/user/selEmail`,this.userForm).then(function (res) {
                    if (res && res.data.result.code == '0') {

                        callback()
                    } else if (res && res.data.result.code == '1') {
                        callback(new Error('邮箱已存在'))
                    }

                })
            }
            return {
                //条件搜索对象
                userFormData:{},
                //表格数据
                tableData:[],
                //每页显示的条数
                pageSize: 5,
                //当前的显示的页码
                currentPage:1,
                //总条数
                total:0,
                //分配角色弹出框显示
                fenRoleDialog:false,
                //所有角色:
                roleAll:[],
                //用户具有的角色:
                userRole:[],
                //分配角色的用户id
                userId:0,
                //添加用户弹出框显示状态
                editUserDialog:false,
                //添加用户表单信息
                userForm:{
                    avatar:''
                },
                token:'',
                // 用户表单校验数据:
                userFormRules:{
                    loginName:[{required:true,message:"登录名不可为空",trigger:'blur'}],
                    userName:[{ required: true, message: '用户不可为空',trigger: 'blur'},
                            { validator: validateAnotherUserName, trigger: 'blur'}],
                    phonenumber:[{ required: true, message: '手机号不可为空',trigger: 'blur'},
                             { validator: validateAnotherPhone,trigger: 'blur'}],
                    email:[{ required: true, message: '邮箱不可为空',trigger: 'blur'},
                        { validator: validateAnotherEmail,trigger: 'blur'}],

                },
            }
        },
        created() {
            //获取用户的信息
            this.initUser();
            this.gettoken();
        },
        methods:{


            //当改变没有显示的条数时触发该方法
            handleSizeChange(v){
                this.pageSize=v
                this.initUser();
            },
            //切换页码时触发该方法
            handleCurrentChange(v){
                this.currentPage=v
                this.initUser();
            },
            initUser(){
                var that=this;
                this.$http.post(`/system/user/sel/${this.currentPage}/${this.pageSize}`,this.userFormData).then(function (re) {
                    that.tableData=re.data.result.records;
                    that.total=re.data.result.total;

                })
            },
            //修改启用禁用状态
            switchStatus(userId,status){
                this.$http.put(`/system/user/up/${userId}/${status}`).then(function (re) {

                })
            },
            //查询所有角色和用户拥有的角色
            showUserRole(userId){
                this.fenRoleDialog=true;
                this.userId=userId;
                var that=this;

                this.$http.get(`/system/role/sel/${userId}`).then(function (resp) {
                    that.roleAll=resp.data.result.roleAll;
                    that.userRole=resp.data.result.userRole;
                    console.log(that.userRole)
                })
            },
            //确认分配角色
            confirmFenRole(){
                this.fenRoleDialog=false;
                this.$http.get(`/system/role/insRole/${this.userId}?userRole=`+this.userRole).then(function (resp) {
                   
                })
            },
            //添加修改用户信息
            editUserBtn(){
                var that = this;

                this.$refs.userFormRef.validate((valid)=>{
                    if(valid) {//valid表示校验通过
                        //进行id判断,如果id不为空则回显数据,走修改,如果id为空,则走添加

                        if(this.userForm.userId!=null) {
                            this.$http.put(`/system/user/updateUserById`,this.userForm).then(function (r) {
                                that.$message.success(r.data.message);
                                that.editUserDialog=false;
                                that.initUserTable();

                            })
                        }else{
                            this.$http.post(`/system/user/insertUser`,this.userForm).then(function (r) {
                                console.log(r);
                                that.$message.success(r.data.message);
                                that.editUserDialog=false;
                                that.initUserTable();

                            })
                        }
                        that.userForm={};
                    }
                })
            },
            //修改回显
            selById(userId){
                this.editUserDialog=true;
                var that=this;
                this.$http.get(`/system/user/selById/${userId}`).then(function (resp) {
                    that.userForm=resp.data.result.userInfo;
                })
            },
            //删除用户
            del(userId){
                var that=this;
                this.$http.delete(`/system/user/del/${userId}`).then(function (resp) {
                    that.$message.success("删除成功");
                    that.initUser();
                    // location.reload();
                })
                this.currentPage=1;
            },
            resetForm(){

                this.$refs.userFormRef.resetFields();
                this.editUserDialog = false;
            },
            handleAvatarSuccess(res){
                //将上传后返回的路径赋值给imageurl
                this.userForm.avatar = res;
            },
            // 上传前格式和图片大小限制
            beforeAvatarUpload(file) {
                const type = file.type === 'image/jpeg' || 'image/jpg' || 'image/webp' || 'image/png'
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!type) {
                    this.$message.error('图片格式不正确!(只能包含jpg，png，webp，JPEG)')
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!')
                }
                return type && isLt2M
            },
            gettoken(){
                this.token = sessionStorage.getItem("token");
            },
            handleClose(){
                this.$refs.userFormRef.resetFields();
                this.editUserDialog = false;
            }

        }
    }
</script>

<style >
    .avatars {
        width: 55px;
        height: 55px;
        border-radius: 50%;
    }
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 80px;
        height: 80px;
        line-height: 178px;
        text-align: center;
    }


</style>